package com.dj.mingkong.common.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Objects;

public class Md5Util {
    private static final Logger log = LoggerFactory.getLogger(Md5Util.class);

    public Md5Util() {
    }

    public static String sign(String text, String inputCharset) {
        if (log.isDebugEnabled()) {
            log.debug("签名文本text:{}, 输入类型：{}", text, inputCharset);
        }

        return DigestUtils.md5Hex(getContentBytes(text, inputCharset));
    }

    public static String sign(String text) {
        if (log.isDebugEnabled()) {
            log.debug("签名文本text:{}, 输入类型：{}", text, StandardCharsets.UTF_8);
        }

        return DigestUtils.md5Hex(getContentBytes(text, StandardCharsets.UTF_8.toString()));
    }

    public static boolean verify(String text, String sign, String key, String inputCharset) {
        text = text + key;
        String mysign = DigestUtils.md5Hex(getContentBytes(text, inputCharset));
        return mysign.equals(sign);
    }

    private static byte[] getContentBytes(String content, String charset) {
        if (charset != null && !"".equals(charset)) {
            try {
                return content.getBytes(charset);
            } catch (UnsupportedEncodingException var3) {
                throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
            }
        } else {
            return content.getBytes();
        }
    }

    private static byte[] md5(String s) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes(StandardCharsets.UTF_8));
            return algorithm.digest();
        } catch (Exception var3) {
            log.error("MD5 Error...", var3);
            return null;
        }
    }

    private static String toHex(byte[] hash) {
        if (hash == null) {
            return null;
        } else {
            StringBuilder buf = new StringBuilder(hash.length * 2);

            for (int i = 0; i < hash.length; ++i) {
                if ((hash[i] & 255) < 16) {
                    buf.append("0");
                }

                buf.append(Long.toString((long) (hash[i] & 255), 16));
            }

            return buf.toString();
        }
    }

    public static String hash(String s) {
        try {
            return new String(((String) Objects.requireNonNull(toHex(md5(s)))).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
        } catch (Exception var2) {
            log.error("not supported charset...", var2);
            return s;
        }
    }
}
